package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.utils.R;
import com.atguigu.entity.to.SkuReductionTo;
import com.atguigu.entity.to.SpuBoundTo;
import com.atguigu.entity.to.es.SkuESModel;
import com.atguigu.entity.vo.SkuHasStokeVo;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.entity.vo.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

//@Log4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVO spuSaveVO) {
        //1.保存spu基本信息->pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVO,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2.保存spu图片集->pms_spu_images
        List<String> images = spuSaveVO.getImages();
        List<SpuImagesEntity> collect = images.stream().map(image -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(image);
            return spuImagesEntity;
        }).filter(image->{
            return !StringUtils.isEmpty(image.getImgUrl());
        }).collect(Collectors.toList());
        spuImagesService.saveSpuImages(collect);

        //3.保存spu详情大图->pms_spu_info_desc
        List<String> decripts = spuSaveVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decripts));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //4.保存spu属性信息->pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrs = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity entity = new ProductAttrValueEntity();
            BeanUtils.copyProperties(attr, entity);

            AttrEntity attrEntity = attrService.getById(entity.getAttrId());
            entity.setAttrName(attrEntity.getAttrName());
            entity.setAttrValue(attrEntity.getValueSelect());
            entity.setAttrSort(1);

            entity.setSpuId(spuInfoEntity.getId());
            entity.setQuickShow(attr.getShowDesc());

            return entity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrs);

        //5.保存spu成长信息->gulimall_sms数据库->sms_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        Bounds bounds = spuSaveVO.getBounds();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeignService.saveBoundInfo(spuBoundTo);
        if (r1.getCode() != 0){
            log.error("远程保存sku积分信息失败！！！");
        }


        //6.保存sku信息
        List<Skus> skus = spuSaveVO.getSkus();
        if (skus != null && skus.size() > 0){

            skus.forEach(sku->{
                String defaultImg = "";
                for (Images image: sku.getImages()) {
                    if (image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }

                //6.1 保存sku基本信息->pms_sku_info
                SkuInfoEntity infoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,infoEntity);
                infoEntity.setSpuId(spuInfoEntity.getId());
                infoEntity.setBrandId(spuInfoEntity.getBrandId());
                infoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                infoEntity.setSaleCount(0L);
                infoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(infoEntity);

                Long skuId = infoEntity.getSkuId();

                //6.2 保存sku图片集->pms_sku_images
                List<SkuImagesEntity> entities = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());

                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(entities);

                //6.3 保存sku属性信息
                List<Attr> skuattrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> attrValueEntities = skuattrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValueEntities);

                //6.4 保存sku详情图片
//                List<String> descar = sku.getDescar();

                //6.4 保存sku活动信息->gulimall_sms数据库,需要保存以下三个数据

                //6.4.1 保存sku折扣信息->sms_sku_ladder
                //6.4.2 保存sku满减信息->sms_sku_full_reduction
                //6.4.3 保存sku会员价格信息->sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 && skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r = couponFeignService.saveSkuReductionInfo(skuReductionTo);

                    if (r.getCode() != 0){
                        log.error("远程保存sku信息失败！！！");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

//    status:
//    key:
//    brandId: 0
//    catelogId: 0
    @Override
    public PageUtils queryPageCodition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("id",key).or().like("spu_name",key).or().like("spu_description",key);
            });
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @GlobalTransactional
    @Transactional
    @Override
    public void up(Long spuId) {
        //组装数据
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuid(spuId);
        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        if (skuIdList != null && skuIdList.size() > 0){
            //TUDO 查询当前sku到所有可以用来检索到属性
            List<ProductAttrValueEntity> attrEntitys = productAttrValueService.listAttrsBySpuId(spuId);
            List<Long> attrids = attrEntitys.stream().map(attrEntity -> {
                return attrEntity.getAttrId();
            }).collect(Collectors.toList());

            //查询可搜索的属性id
            List<Long> searchAttrIds = attrService.getSearchAttrIds(attrids);

            Set<Long> idSet = new HashSet<>(searchAttrIds);

            List<SkuESModel.Attrs> attrs = attrEntitys.stream().filter(item -> {
                return idSet.contains(item.getAttrId());
            }).map(item->{
                SkuESModel.Attrs attr = new SkuESModel.Attrs();
                BeanUtils.copyProperties(item,attr);

                return attr;
            }).collect(Collectors.toList());

            //TUDO 发生远程调用，到库存系统查询是否有库存
            Map<Long, Boolean> hasstokeMap = null;
            try {
                R hasstoke = wareFeignService.hasstoke(skuIdList);
                TypeReference<List<SkuHasStokeVo>> typeReference = new TypeReference<List<SkuHasStokeVo>>() {
                };
                List<SkuHasStokeVo> data = hasstoke.getData(typeReference);
                hasstokeMap = data.stream().collect(Collectors.toMap(SkuHasStokeVo::getSkuId, item -> item.isHasStoke()));
            } catch (Exception e) {
                e.printStackTrace();
            }

            Map<Long, Boolean> finalHasstokeMap = hasstokeMap;
            List<SkuESModel> esModelList = skuInfoEntities.stream().map(skuEntity -> {
                SkuESModel esModel = new SkuESModel();
                BeanUtils.copyProperties(skuEntity, esModel);

                esModel.setSkuPrice(skuEntity.getPrice());
                esModel.setSkuImg(skuEntity.getSkuDefaultImg());

                //hasStock hotScore
                //TUDO 发生远程调用，到库存系统查询是否有库存
                if (finalHasstokeMap == null) {
                    esModel.setHasStock(true);
                } else {
                    esModel.setHasStock(finalHasstokeMap.get(skuEntity.getSkuId()));
                }

                //TUDO 热度评分 默认0
                esModel.setHotScore(0L);

                //TUDO查询品牌信息和分类名称信息
                BrandEntity brand = brandService.getById(esModel.getBrandId());
                if (brand != null){
                    esModel.setBrandName(brand.getName());
                    esModel.setBrandImg(brand.getLogo());
                }

                CategoryEntity category = categoryService.getById(esModel.getCatalogId());
                if (category != null){
                    esModel.setCatalogName(category.getName());
                }

                //设置属性
                esModel.setAttrs(attrs);

                return esModel;
            }).collect(Collectors.toList());

            //TUDO 将数据发送给es服务进行保存
            R r = searchFeignService.saveProduct(esModelList);
            if (r.getCode() == R.getSUCCESS()){
                //修改上架状态
                baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
            }else {

            }
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoByskuId(Long skuId) {

        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);
        Long spuId = skuInfo.getSpuId();

        SpuInfoEntity spuEntity = getById(spuId);
        return spuEntity;
    }

}